package com.alageek.personalblog.web;

import com.alageek.personalblog.common.constant.BlogConstant;
import com.alageek.personalblog.entity.doo.Comment;
import com.alageek.personalblog.entity.doo.CommentReply;
import com.alageek.personalblog.entity.query.CommentQuery;
import com.alageek.personalblog.entity.vo.CommentVo;
import com.alageek.personalblog.service.CommentReplyService;
import com.alageek.personalblog.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.List;

/**
 * 评论控制器
 * @author AlaGeek
 */
@Slf4j
@Controller
@RequestMapping("/comment")
public class CommentController {

    private final CommentService commentService;
    private final CommentReplyService commentReplyService;

    public CommentController(CommentService commentService, CommentReplyService commentReplyService) {
        this.commentService = commentService;
        this.commentReplyService = commentReplyService;
    }

    @GetMapping("/list/{postId}")
    public String list(@PathVariable("postId") Integer postId, ModelMap modelMap) {
        List<CommentVo> commentList = commentService.findByPostId(postId);
        for (CommentVo commentVo : commentList) {
            commentVo.setCommentReplyVoList(commentReplyService.findByCommentId(commentVo.getId()));
        }
        modelMap.addAttribute(BlogConstant.ATTR_NAME_COMMENT_LIST, commentList);
        return "blog-detail :: commentList";
    }

    @PostMapping("/add")
    public String add(CommentQuery commentQuery) {
        commentQuery.setCreateTime(new Date());
        if (commentQuery.getCommentId() == -1) {
            // 文章评论
            Comment comment = new Comment(commentQuery);
            commentService.saveSelective(comment);
        } else {
            // 评论回复
            CommentReply commentReply = new CommentReply(commentQuery);
            commentReplyService.saveSelective(commentReply);
        }
        return "redirect:/comment/list/" + commentQuery.getPostId();
    }

}
